
<template>
  <el-badge
    :value="unreadcount"
    class="item"
    :max="99"
    :offset="[-2, 0]"
    :show-zero="false"
    style="margin-right: 24px"
  >
    <img
      src="@/assets/page/notice.png"
      style="width: 24px; height: 24px; cursor: pointer"
      @click="goMessage()"
      alt=""
    />
  </el-badge>
</template>

<script setup>
import { ElNotification } from 'element-plus'
import { http } from '@/utils/http'
import config from '@/config'
import WS from '@/utils/ws.js'
const languageJson = inject('languageJson')
const languageType = inject('languageType')
const router = useRouter()
const unreadcount = ref(0)
let uncountIntervalId

const audio = new Audio()
const ws = new WS({
  url: `ws://47.76.250.92:9996/sp/message/`,
  onMessage(data) {
    console.log(data)
    if (data.level != undefined) {
      if (data.level !== 3) {
        audio.src = 'http://tools.app.qubit-dance.com/sound/success.mp3'
        audio.play()
      } else {
        audio.src = 'http://tools.app.qubit-dance.com/sound/defeat.mp3'
        audio.play()
      }
      ElNotification({
        title: languageJson.value.notice.message,
        icon: '',
        customClass: 'message_class',
        position: 'top-left',
        dangerouslyUseHTMLString: true,
        message: data.message,

        //  <div>
        //   <span style="margin-right: 8px;width: 32px;padding: 0 4px;height: 16px;background: ${
        //     colors[data.level]
        //   };color: #fff">${levels[data.level]}</span><span>${data.message}
        //   </span>
        // </div>
        onClick() {
          goMessage()
        },
      })
    }
  },
})


const levels = ref({
  1: languageJson.value.notice.ordinary,
  2: languageJson.value.notice.important,
  3: languageJson.value.notice.warnt,
  4: languageJson.value.notice.success,
})
const colors = { 1: '#3711d8;', 2: '#ff5f58', 3: '#feac2e', 4: '#1cc535' }

const goMessage = () => {
  // router.replace('message')
  if (config.isWeb) {
    window.open(`/#/message`)
  } else {
    let a = {
      value: 'message',
      label: languageJson.value.notice.messageCenter,
    }
    window.SDK.send('openWeb', a)
  }
}

const getunreadcount = () => {
  clearInterval(uncountIntervalId)
  http.get('/message/unread_count').then(res => {
    unreadcount.value = res.data.unread_count
    uncountIntervalId = setInterval(() => {
      getunreadcount()
    }, 10000)
  })
}

onMounted(() => {
  getunreadcount()
})
onUnmounted(() => {
  clearInterval(uncountIntervalId)
  ws.close()
})
</script>

<style lang="scss" scoped>
</style>

<style>
.message_class {
  width: 384px;
  padding: 20px 24px;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.2);
  background-color: #fff;
  border-radius: 0;
}
.message_class .el-notification__icon {
  display: none;
}
.message_class .el-notification__group {
  margin: 0;
}
.message_class .el-notification__content {
  margin-top: 16px;
}
</style>